var Product = function(){
	
};

Product.prototype.initProducts = function(urls) {
	this.urls=urls;
	this.productsTypeList = {};
	this.typeNameSource = new Array();
	var urlWebService=  this.urls["urlBackend"]+ "/ProductService/searchProductByFilter";
	var self = this;
	$.ajax({
		url: urlWebService,
		//data: "{'product':[]}", exampĺe for seding a list as parameter in CXF rest servoce
		data : "_type=json",
		contentType : 'application/json',
		dataType : 'json',
		type : 'GET',
		success: function (data){
			self.getProductTypes();
			self.initGrid(data);
			self.initButtons();
		}
	});
	
};

Product.prototype.generateRow = function (){
	var self=this;
	var urlWebService = self.urls["urlBackend"] + "/ProductService/createTmpObject";
	$.ajax({
		url: urlWebService,
		data : "_type=json",
		contentType : 'application/json',
		dataType : 'json',
		type : 'POST',
		success: function (data){
			var newRow = {
					'model.productView.id' : data.Product[0].id,
			        'model.productView.name' : data.Product[0].name ,            
			        'model.productView.code' : data.Product[0].code ,
			        'model.productView.quantity' : data.Product[0].quantity  ,
			        'model.productView.price' : data.Product[0].price  ,
			        'typeName' :  data.Product[0].productType.name ,
			        'model.productView.description' : ''  ,
			        'model.productView.percSale': ''  ,
			        'model.productView.priceOffer' : ''  ,
			        'model.productView.dateSaleFrom' : ''  ,
			        'model.productView.dateSaleUntil' : ''
				};
			$("#jqxgrid").jqxGrid('addrow', null, newRow)
		}
	});
};

Product.prototype.deleteProduct = function (productId,commit){
	var self = this;
	$("#jqxWidget").block();
	$.ajax({
        url: self.urls["deleteProduct"],
		cache: false,
        data: { 'model.productView.id' : productId},
        success: function (data, status, xhr) {
			commit(true);
			$("#jqxWidget").unblock();
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			commit(false);
			$("#jqxWidget").unblock();
		}
	});
};

Product.prototype.initButtons = function (){
	var self = this;
	$("#addrowbutton,#deleterowbutton").jqxButton({ theme: "darkblue" });
	
	$("#addrowbutton").bind('click', function () {
        var rowscount = $("#jqxgrid").jqxGrid('getdatainformation').rowscount;
        self.generateRow();
    });
	
	$("#deleterowbutton").bind('click', function () {
        var selectedrowindex = $("#jqxgrid").jqxGrid('getselectedrowindex');
        var rowscount = $("#jqxgrid").jqxGrid('getdatainformation').rowscount;
        if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
            var id = $("#jqxgrid").jqxGrid('getrowid', selectedrowindex);
            $("#jqxgrid").jqxGrid('deleterow', id);
        }
    });
}

Product.prototype.getDateFormatted = function (dateValue) {
	return dateValue.getDate() + "/" + (dateValue.getMonth()+1) + "/" + dateValue.getFullYear(); 
};

Product.prototype.initGrid= function (data){
	var theme = "darkblue";
	var self = this;
	 var source =
    {
        localdata: data,
        datatype: "json",
        addrow: function (rowid, rowdata, position, commit) {
            commit(true);
        },
        deleterow: function (rowid, commit) {
        	self.deleteProduct(rowid,commit);
        },
        updaterow: function (rowid, rowdata, commit) {
  			self.saveProduct(rowid, rowdata, commit);
        },
        datafields:
        [
            { name: 'model.productView.id', type: 'number' , map : 'id' },
            { name: 'model.productView.name', type: 'string' , map : 'name' },            
            { name: 'model.productView.code', type: 'string' , map : 'code' },
            { name: 'model.productView.quantity', type: 'number' , map : 'quantity'  },
            { name: 'model.productView.price', type: 'number' , map : 'price'  },
            { name: 'typeName', type: 'string' , map: 'productType>name'  },
            { name: 'model.productView.description', type: 'string' , map : 'description'  },
            { name: 'model.productView.percSale', type: 'number' , map : 'percSale'  },
            { name: 'model.productView.priceOffer', type: 'number' , map : 'priceOffer'  },
            { name: 'model.productView.dateSaleFrom', type: 'date' , map : 'dateSaleFrom'  },
            { name: 'model.productView.dateSaleUntil', type: 'date', map : 'dateSaleUntil'  }            
        ],
        id : 'id' ,
        root : "Product"
    };
    
    var dataAdapter = new $.jqx.dataAdapter(source);
    
    // initialize jqxGrid
    $("#jqxgrid").jqxGrid(
    {
        width: 1124,
        source: dataAdapter,
        editable: true,
        theme: theme,
        editmode: 'dblclick',
        //selectionmode: 'multiplecellsadvanced',
        columns: [
          { text: 'Id', columntype: 'hidden', datafield: 'model.productView.id', width: 40 , editable : false },
          { text: 'Name', columntype: 'textbox', datafield: 'model.productView.name', width: 180 },
          { text: 'code', columntype: 'textbox', datafield: 'model.productView.code', width: 40 },
          { text: 'Product Type', columntype: 'dropdownlist', datafield: 'typeName', width: 100 ,
        	  createeditor: function (row, cellvalue, editor) {
        		  editor.jqxDropDownList({ source:self.typeNameSource});
              }
          },
          { text: 'description', columntype: 'textbox', datafield: 'model.productView.description', width: 195 },
          { text: 'Sale %', columntype: 'numberinput' , datafield: 'model.productView.percSale', width: 70, align: 'right', cellsalign: 'right', cellsformat: 'd',
              validation: function (cell, value) {
                  if (value < 0 || value > 100) {
                      return { result: false, message: "Quantity should be in the 0-150 interval" };
                  }
                  return true;
              },
              createeditor: function (row, cellvalue, editor) {
                  editor.jqxNumberInput({ decimalDigits: 2, digits: 7 });
              }
          },
          { text: 'Offer price', columntype: 'numberinput' , datafield: 'model.productView.priceOffer', width: 70, align: 'right', cellsalign: 'right', cellsformat: 'c2',
              validation: function (cell, value) {
                  if (value < 0 || value > 150) {
                      return { result: false, message: "Quantity should be in the 0-150 interval" };
                  }
                  return true;
              },
              createeditor: function (row, cellvalue, editor) {
                  editor.jqxNumberInput({ decimalDigits: 2, digits: 7 });
              }
          },
          {text: 'Sale From', datafield: 'model.productView.dateSaleFrom', columntype: 'datetimeinput', width: 110, align: 'right', cellsalign: 'right', cellsformat: 'dd/MM/yyyy',
          validation: function (cell, value) {
                  if (value == "")
                     return true;

                  var year = value.getFullYear();
                  if (year >= 2014) {
                      return { result: false, message: "Ship Date should be before 1/1/2014" };
                  }
                  return true;
              }
          },
          {text: 'Date Created', datafield: 'model.productView.dateSaleUntil', columntype: 'datetimeinput', width: 110, align: 'right', cellsalign: 'right', cellsformat: 'dd/MM/yyyy',
              validation: function (cell, value) {
                      if (value == "")
                         return true;

                      var year = value.getFullYear();
                      if (year >= 2014) {
                          return { result: false, message: "Ship Date should be before 1/1/2014" };
                      }
                      return true;
                  }
          },
          {
              text: 'Quantity', datafield: 'model.productView.quantity', width: 70, align: 'right', cellsalign: 'right', columntype: 'numberinput',
              validation: function (cell, value) {
                  if (value < 0 || value > 150) {
                      return { result: false, message: "Quantity should be in the 0-150 interval" };
                  }
                  return true;
              },
              createeditor: function (row, cellvalue, editor) {
            	  editor.jqxNumberInput({ decimalDigits: 2, digits: 7 });
              }
          },
          { text: 'Price', datafield: 'model.productView.price', align: 'right', cellsalign: 'right', cellsformat: 'c2', columntype: 'numberinput',
              validation: function (cell, value) {
                  if (value < 0 || value > 150000) {
                      return { result: false, message: "Price should be in the 0-150000 interval" };
                  }
                  return true;
              },
              createeditor: function (row, cellvalue, editor) {
                  editor.jqxNumberInput({ digits: 3 });
              }
          }
        ]
    });
    self.bindGridEvent();
};

Product.prototype.saveProduct = function (rowid, rowdata, commit){
	$("#jqxWidget").block();
	var self=this;
   	var dataArray = $.extend({},rowdata); 
   	var dateSaleFrom = rowdata["model.productView.dateSaleFrom"];
   	var dateSaleUntil = rowdata["model.productView.dateSaleUntil"];
   	if(rowdata.typeName!=undefined && rowdata.typeName!="" ){
   		dataArray["model.productView.productType.id"]=self.productsTypeList[rowdata.typeName].id;
   	}
   	if(dateSaleFrom!=undefined && dateSaleFrom!="" ){
   		dataArray["model.productView.dateSaleFrom"]=self.getDateFormatted(dateSaleFrom);
   	}
   	if(dateSaleUntil!=undefined && dateSaleUntil!="" ){
   		dataArray["model.productView.dateSaleUntil"]=self.getDateFormatted(dateSaleUntil);
   	}
   	$.ajax({
   		url: self.urls["saveProduct"],
   		data: dataArray,
   		success: function(data, status, xhr)  {
   			commit(true);		
   			$("#jqxWidget").unblock();
   			$("#cellendeditevent").html("Update <span style='color:blue'><strong>SUCCESS</strong></span>, Column: " + args.datafield + ", Row: " + (1 + args.rowindex) + ", Value: " + args.value);
   			
   		},
   		error: function(jqXHR, textStatus, errorThrown) {
   			commit(false);
   			$("#cellendeditevent").html("Update <span style='color:red'><strong>ERROR</strong></span>, Column: " + args.datafield + ", Row: " + (1 + args.rowindex) + ", Value: " + args.value);
   			$("#jqxWidget").unblock();
   		}
   	});
};

Product.prototype.bindGridEvent = function (){
	var self= this;
    // events
    $("#jqxgrid").on('cellendedit', function (event) {
        var args = event.args;
        $("#cellendeditevent").text("Update SUCCESS, Column: " + args.datafield + ", Row: " + (1 + args.rowindex) + ", Value: " + args.value);
    });	
};

Product.prototype.getProductTypes = function (dropDownList){
	var self = this;
	var urlWebService= self.urls["urlBackend"] + "/ProductTypeService/searchProductTypeByFilter";
	$.ajax({
		url: urlWebService,
		data : "_type=json",
		contentType : 'application/json',
		dataType : 'json',
		type : 'GET',
		success: function (data){
			var typeName= new Array();
			for (i =0 ; i<data.ProductType.length;i++){
				self.typeNameSource[i]=data.ProductType[i].name;
				self.productsTypeList[data.ProductType[i].name]=data.ProductType[i];
			}
		}
	});
};
